package wsz.rocketMq.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import wsz.rocketMq.service.PhoneService;
import wsz.rocketMq.util.Constants;

import javax.servlet.http.HttpServletRequest;

/**
 * 商品秒杀业务
 * @author wsz
 * @date 2022/3/2 10:35
 **/
@Controller
@RequestMapping("phone")
public class PhoneController {
    @Autowired
    private PhoneService phoneService;

    /**
     * 跳转手机详情页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/{id}")
    public String findById(@PathVariable Long id, Model model, HttpServletRequest request) {
        model.addAttribute("phone", phoneService.findById(id));

        // 防刷限制，限制每分钟100次
        initSession(request);

        return "phone";
    }

    private void initSession(HttpServletRequest request) {
        request.getSession().setAttribute(Constants.REFRESH_CTR, Constants.REFRESH_CTR_TIMES);
        request.getSession().setAttribute(Constants.REFRESH_CTR_TIME, System.currentTimeMillis());
    }

    @ResponseBody
    @GetMapping(value = "kill/{id}")
    public JSONObject phoneKill(@PathVariable Long id, HttpServletRequest request) {
        // 防刷限制
        Object attribute = request.getSession().getAttribute(Constants.REFRESH_CTR);
        System.out.println(attribute);
        if (attribute == null) {
            initSession(request);
        } else {
            Integer times = (Integer) attribute;
            if (times > 0) {
                request.getSession().setAttribute(Constants.REFRESH_CTR, --times);
            } else {
                // 判断是否超时
                Long start = (Long) request.getSession().getAttribute(Constants.REFRESH_CTR_TIME);
                Long now = System.currentTimeMillis();
                if (now - start < 1000*60*1) {
                    JSONObject res = new JSONObject();
                    res.put("status", false);
                    res.put("msg", "稍后重试");
                    return res;
                } else {
                    initSession(request);
                }
            }
        }

        // 执行秒杀
        return phoneService.kill(id);
    }
}
